<?php

class GoodsMode extends SiteMode {
    /** @return GoodsMode */
    public static function init() {
        return parent::init();
    }
    // 商品列表，各种搜索方式 $orderBy可以是null|sale|comment|base_price|new
    function getList($shop_id = null,$label_id = null,$goods_cat_ids = null,$text = null,
                     $orderBy = null, $asc = false,$rows = 30,$offset = 0,$countLimit = true){
        $rows=(int)$rows;
        $offset=(int)$offset;
        if(!$countLimit) $rows = null;
        $data=array(
            'goods G'=>array('gopen_id'),
            'goods_price GP'=>array()
        );
        $condition=array(
            'G.`gopen_id`=GP.`gopen_id`',
            'G.enable'=>1,
            'G.`price_id`=GP.`id`',
            'G.site_id'=>$this->siteId
        );
        $condition['G.shop_id']=isset($shop_id)? (int)$shop_id: null;
        $condition['G.name']=isset($text)? "like  %".str_replace(array('　',' '), '%', $text)."% ": null;
        if(isset($goods_cat_ids)){
            $condition[]=$this->db->getIdCondition($goods_cat_ids,"goods_cat_id");
        }
        if(isset($label_id)){
            $condition[]="FIND_IN_SET(".(int)$label_id.",G.`label_ids`)";
        }
        switch($orderBy){
            case 'sale':$orderBy = 'G.sale';break;
            case 'comment':$orderBy = 'G.comment';break;
            case 'base_price':$orderBy = 'GP.base_price';break;
            case 'time':$orderBy = 'G.create_time';break;
            default:$orderBy = 'G.sale,G.comment';
        }
        $sql=$this->db->selectSql($data,$condition,$rows,$offset,$orderBy,$asc);
        list($re,$total)=$this->db->getList($sql);
        $gopen_ids=array_map(function($value){return $value['gopen_id'];},$re);
        return array($gopen_ids, $total);
    }
    function sortGoods(&$goodsList, $orderBy, $asc){
        $orderByArray=array("comment","base_price","sale","create_time");
        if(!in_array($orderBy,$orderByArray)) {
            return false;
        }
        usort($goodsList,function($a,$b)use($orderBy,$asc){
            switch($orderBy){
                case 'sale': return ($asc?1:-1)*($a['sale']-$b['sale']); break;
                case 'comment':return ($asc?1:-1)*($a['comment']-$b['comment']);break;
                case 'base_price':return ($asc?1:-1)*($a['price']['base_price']-$b['price']['base_price']);break;
                default:return ($asc?1:-1)*(strtotime($a['create_time'])-strtotime($b['create_time']));break;
            }
        });
        return true;
    }
    //获得某分类下商品数量
    function getTotalByCatId($goods_cat_id){
        $sql="SELECT count(1) FROM `goods` WHERE `enable`=1 AND `goods_cat_id`=? and site_id=?";
        return $this->db->getValue($sql,(int)$goods_cat_id, $this->siteId);
    }
    //获得详细商品信息
    function getDetailInfo($gopen_ids){
        if(empty($gopen_ids)) return array();
        $data=array(
            'goods G'=>array('*'),
//            'shop_info SI'=>array('qq', 'tel', 'company','create_time'=>'shop_create_time',
//                'enable'=>'shop_enable','latitude'=>'shop_latitude','longitude'=>'shop_longitude'),
            'goods_cat GC'=>array('name'=>'goods_cat'),
            'tip T'=>array('id'=>'tip_id','title'=>'tip_title','content'=>'tip_content'),
            'picture P'=>array('url'=>'thumb')
        );
        $condition=array(
            'G.enable'=>1,
//            'G.`shop_id`=SI.`id`',
            'G.`goods_cat_id`=GC.`id`',
            'G.`tip_id`=T.`id`',
            'G.`thumb_pic`=P.`id`',
            'G.site_id'=>$this->siteId
        );
        $condition[]=$this->db->getIdCondition((array)$gopen_ids,'gopen_id');
        $sql= $this->db->selectSql($data,$condition);
        $r=$this->db->getAll($sql);
        foreach ($r as &$v) {
            $v['shop']=ShopMode::init()->getDetail($v['shop_id']);
            $v['pic']=PictureModule::init('picture')->getDetail($v['pic_ids']);
            $v['label']=LabelModule::init()->getListByIds($v['label_ids']);
            $v['price']=$this->getPrice($v['price_id']);
            $v['attr']=$this->getAttrList($v['gopen_id']);
            //comment先注释掉，因为评论需要搜出所有的
//            $r['comment']=CommentModule::init('goods_comment','user','gopen_id')->getList(null,$gopen_id);
        }
        return is_array($gopen_ids)? $r: reset($r);
    }
    //获得商品简要信息（goods表+Thumb+Price）
    function getSimpleInfo($gopen_ids){
        if(empty($gopen_ids)) return array();
        $data=array(
            'goods G'=>array('*','id'=>'goods_id'),
            'picture P'=>array('url'=>'thumb')
        );
        $condition=array(
            'G.enable'=>1,
            'G.`thumb_pic`=P.`id`',
            'G.site_id'=>$this->siteId
        );
        $condition[]=$this->db->getIdCondition((array)$gopen_ids,'gopen_id');
        $sql= $this->db->selectSql($data,$condition);
        //保持顺序
        if(!empty($gopen_ids)&&is_array($gopen_ids)){
            $sql .= ' order by FIELD(gopen_id,' ;
            foreach ($gopen_ids as $key => $value) {
                if($key != 0) $sql.=',';
                $sql .= $value;
            }
            $sql .=')';
        }
        $r=$this->db->getAll($sql);
        foreach ($r as &$v) {
            $v['price']=$this->getPrice($v['price_id']);
        }
        return is_array($gopen_ids)? $r: reset($r);

    }

    //根据gopen_id获得有效商品id
    function getId($gopen_id){
        $sql="SELECT `id` FROM `goods` WHERE `gopen_id`=? AND `enable`=1 and site_id=?";
        return $this->db->getValue($sql,$gopen_id, $this->siteId);
    }
    //根据id获得有效商品的gopen_id
    function getGopenId($id){
        $sql="SELECT `gopen_id` FROM `goods` WHERE `id`=? AND `enable`=1 and site_id=?";
        return $this->db->getValue($sql,$id, $this->siteId);
    }
    //通过id获得所有价格
    function getPrice($price_id){
        $sql="SELECT * FROM `goods_price` WHERE `id`=?";
        return $this->db->getOne($sql,$price_id);
    }
    function getPriceOfGoods($gopen_id){
        $priceId=$this->getPriceId($gopen_id,true);
        return $this->getPrice($priceId);
    }
    //获得商品基本价格
    function getBasePrice($price_id){
        $sql="SELECT `base_price` FROM `goods_price` WHERE `id`=?";
        return (double)$this->db->getValue($sql,$price_id);
    }
    //获得合适的价格
    function getPriceByNum($price_id,$number){
        $r=$this->getPrice($price_id);
        $number=(int)$number;
        $price=$r['base_price'];
        if(!empty($r['low']) && $r['low'] > $number){
            $price=$r['base_price'];
        }elseif(!empty($r['medium']) && $r['medium'] > $number){
            $price=$r['medium_price'];
        }elseif(!empty($r['high_price'])){
            $price=$r['high_price'];
        }
        return (double)$price;
    }
    //添加商品,返回goods_id,也就是gopen_id
    function add($shop_id,$name,$goods_cat_id,$unit,$detail,$stock,$pic_ids,$thumb_pic,$tip_id,$price_id,
                 $bonus,$commission,$service_fee,$type= 'normal',$label_ids = null,$qq,$note,$supplier){
        $data['shop_id']=$shop_id;
        $data['name']=$name;
        $data['goods_cat_id']=$goods_cat_id;
        $data['unit']=$unit;
        $data['detail']=$detail;
        $data['stock']=$stock;
        $data['pic_ids']=$pic_ids;
        $data['thumb_pic']=$thumb_pic;
        $data['tip_id']=$tip_id;
        $data['price_id']=$price_id;
        $data['bonus']=$bonus;
        $data['commission']=$commission;
        $data['service_fee']=$service_fee;
        $data['type']=$type;
        $data['label_ids']=$label_ids;
        $data['qq']=$qq;
        $data['note']=$note;
        $data['supplier']=$supplier;
        $data['site_id']=$this->siteId;
        if($this->db->insert('goods',$data)){
            $goods_id=(int)$this->db->insertId();
            $data2['gopen_id']=$goods_id;
            $this->db->update('goods',$goods_id,$data2);
            return $goods_id;
        }
        return -1;
    }
    /**
     * 获得商品信息，无联表
     * @param int $id goods_id|gopen_id
     * @param bool $is_gopen_id
     * @return array
     */
    function getDetailWithoutJoin($ids,$is_gopen_id = true){
        if($is_gopen_id){
            $condition="`enable`=1 AND ".$this->db->getIdCondition($ids,'gopen_id');
        }else{
            $condition= $this->db->getIdCondition($ids,'id');
        }
        $sql="SELECT * FROM `goods` WHERE site_id=? and ".$condition;
        $r=$this->db->getAll($sql, $this->siteId);
        return is_array($ids)? $r: $r[0];
    }

    /**
     * 修改商品，shop_id,type不能改
     * @return int id|0|-1
     */
    function modify($goods_id,$gopen_id,$name,$goods_cat_id,$unit,$detail,$stock,$pic_ids,$thumb_pic, $tip_id,
                        $price_id,$bonus=null,$commission=null,$service_fee=null,$platform_fee=null,$label_ids=null,
                        $qq=null,$note=null,$supplier=null){
        $data['name']=$name;
        $data['goods_cat_id']=$goods_cat_id;
        $data['unit']=$unit;
        $data['detail']=$detail;
        $data['stock']=$stock;
        $data['pic_ids']=$pic_ids;
        $data['thumb_pic']=$thumb_pic;
        $data['tip_id']=$tip_id;
        $data['bonus']=$bonus;
        $data['commission']=$commission;
        $data['service_fee']=$service_fee;
        $data['platform_fee']=$platform_fee;
        $data['label_ids']=$label_ids;
        $data['qq']=$qq;
        $data['note']=$note;
        $data['supplier']=$supplier;
        $oldGoodsData=$this->getDetailWithoutJoin($gopen_id);

        if(!empty($price_id)&& $oldGoodsData['price_id']!=$price_id){
            //price_id变了则新建一条
            foreach($oldGoodsData as $k=>$v){
                if(!isset($data[$k])|| empty($data[$k])) $data[$k]=$v;
            }
            unset($data['id']);
            unset($data['create_time']);
            $data['price_id']=$price_id;
            if($this->db->insert('goods',$data)){
                $sql="UPDATE `goods` SET `enable`= 0 WHERE `id`=?";
                $this->db->sqlExec($sql,$goods_id); //enable=0
                return (int)$this->db->insertId();
            }else{
                return -1;
            }
        }
        return $this->db->update('goods',$goods_id,$data)==1 ? 0:-1;
    }
    /**
     * 删除（隐藏）商品
     * @param $id
     * @return int
     */
    function delete($id){
        $sql="UPDATE `goods` SET `enable`= 0 WHERE `id`=?";
        return $this->db->sqlExec($sql,$id);
    }
    /**
     * 获得商品price_id
     * @param $id   goods_id|gopen_id
     * @param bool $is_gopen_id
     * @return int
     */
    function getPriceId($id,$is_gopen_id = true){
        $goodsInfo=$this->getDetailWithoutJoin($id,$is_gopen_id);
        return (int)$goodsInfo['price_id'];
    }

    //检查商品base_price是否发生改变了
    function checkBasePriceChanged($price_id,$base_price){
        $thisPrice=$this->getBasePrice($price_id);
        return $thisPrice != $base_price;
    }

    /**
     * 判断价格是否变了
     * @param $id   goods_id|gopen_id
     * @param int $price_id
     * @param bool $is_gopen_id
     * @return bool
     */
    function checkPriceIdChanged($id,$price_id,$is_gopen_id = true){
        $price_id=(int)$price_id;
        $thisPriceId=$this->getPriceId($id,$is_gopen_id);
        return $thisPriceId != $price_id;
    }

    //新建一条价格
    function addPrice($gopen_id,$original_price,$base_price,$low = null,
                      $medium = null,$medium_price = null,$high_price = null){
        $data['gopen_id']=$gopen_id;
        $data['original_price']=$original_price;
        $data['base_price']=$base_price;
        $data['low']=$low;
        $data['medium']=$medium;
        $data['medium_price']=$medium_price;
        $data['high_price']=$high_price;
        return $this->db->insert('goods_price',$data) == 1 ? (int)$this->db->insertId():-1;

    }

    /**
     * 修改价格，成功新建返回price_id，成功修改返回0，失败返回-1
     * @return int
     */
    function modifyPrice($price_id,$gopen_id,$original_price,$base_price,$low = null,
                      $medium = null,$medium_price = null,$high_price = null){
        $sql="UPDATE `goods_price` SET `low`=null,`medium`=null,`medium_price`=null,`high_price`=null WHERE `id`=?";
        $setNullRe=$this->db->sqlExec($sql,$price_id);

        $data['original_price']=$original_price;
        $data['gopen_id']=$gopen_id;
        $data['low']=$low;
        $data['medium']=$medium;
        $data['medium_price']=$medium_price;
        $data['high_price']=$high_price;
        if($this->checkBasePriceChanged($price_id,$base_price)){
            //base_price改变了要新建
            $data['base_price']=$base_price;
            return $this->db->insert('goods_price',$data) == 1 ? (int)$this->db->insertId():-1;
        }
        //没改变修改
        return ($this->db->update('goods_price',$price_id,$data)==1) || $setNullRe ? 0:-1;

    }
    //销量增加
    function modifySale($gopen_id,$saleIncNumber){
        $saleIncNumber=(int)$saleIncNumber;
        $sql="UPDATE `goods` SET `sale`=`sale`+$saleIncNumber WHERE `gopen_id`=? AND `enable`=1";
        return $this->db->sqlExec($sql,$gopen_id) == 1;
    }
    //array(array('name'=>'1','stock'=>'1'),array('name'=>'2','stock'=>'2'))
    function addAttr($gopen_id,$attrArray){
        $gopen_id=(int)$gopen_id;
        if(!empty($attrArray)){
            $data['gopen_id']=$gopen_id;
            $r = true;
            foreach ($attrArray as $v) {
                $data['name']=$v['name'];
                $data['stock']=$v['stock'];
                $r = $r && $this->db->insert('goods_attr',$data) == 1;
            }
            return $r;
        }
        return false;
    }
    function modifyAttr($id,$name,$stock){
        $data['name']=$name;
        $data['stock']=$stock;
        return $this->db->update('goods_attr',$id,$data) == 1;
    }
    function deleteAttr($id){
        return $this->db->delete('goods_attr',$id)==1;
    }
    function getAttrDetail($id){
        $sql="SELECT * FROM `goods_attr` WHERE `id`=?";
        return $this->db->getOne($sql,$id);
    }
    function getAttrList($gopen_id){
        $sql="SELECT * FROM `goods_attr` WHERE `gopen_id`=?";
        return $this->db->getAll($sql,$gopen_id);
    }
    //获得shop_id
    function getShopId($gopen_id){
        $goodsInfo=$this->getDetailWithoutJoin($gopen_id,true);
        return !empty($goodsInfo)?(int)$goodsInfo['shop_id']:null;
    }
    //获得商品历史价格
    function getAllPrice($gopen_id){
        $sql="SELECT * FROM `goods_price` WHERE `gopen_id`=? ORDER BY `create_time` DESC";
        return $this->db->getAll($sql,$gopen_id);
    }

    /**
     * 索搜索框下显示的label或者其他地方显示的label
     * @param string $place box|detail|null
     * @return array
     */
    function getLabelByPlace($place = null){
        switch($place){
            case 'box':$con=" AND `show_in_box`=1";break;
            case 'detail':$con=" AND `show_in_detail`=1";break;
            default:$con='';
        }
        $sql="SELECT * FROM `goods_label` WHERE site_id=?  ".$con;
      
        return $this->db->getAll($sql, $this->siteId);
    }

    //下面是购物分享专题
    //分享人详情，下单那用到或者某个弹出框会用到
    function getShareDetail($user_id,$gopen_id){
        $sql="SELECT GS.*,U.`username` FROM `goods_share` GS,`user` U
              WHERE U.`id`=GS.`from_id`
              AND GS.`user_id`=? AND GS.`gopen_id`=?";
        return $this->db->getAll($sql,$user_id,$gopen_id);
    }
    function goodsShareAdd($gopen_id,$user_id,$from_id){
        $gopen_id = (int)$gopen_id;
        $user_id  = (int)$user_id;
        $from_id  = (int)$from_id;
        if($user_id==$from_id) return false;
        if(!$this->db->getExist("SELECT * from `goods_share` where gopen_id=$gopen_id and user_id=$user_id and from_id=$from_id"))
            return $this->db->sqlExec("INSERT INTO `goods_share` (gopen_id,user_id,from_id) values ($gopen_id,$user_id,$from_id)");
        return false;
    }
    function goodsShareBuy($goods_share_id){
        $goods_share_id = (int)$goods_share_id;
        return $this->db->sqlExec("UPDATE `goods_share` SET buy=1 where id=$goods_share_id");
    }
    function goodsShareUsers($from_id,$gopen_id,$num){
        $from_id=(int)$from_id;
        $gopen_id = (int)$gopen_id;
        $num      = (int)$num;
        return $this->db->getList(
            "SELECT SQL_CALC_FOUND_ROWS `user`.username
            from `goods_share` GS,`user`
            where GS.gopen_id=$gopen_id and GS.from_id=$from_id and GS.user_id=`user`.id
            order by GS.id desc
            limit $num"
        );
    }
    //改库存
    function modifyStock($gopen_id,$attr_id,$number){
        $gopen_id=(int)$gopen_id;
        $attr_id=(int)$attr_id;
        $number=$this->db->quote($number);
        $sql="UPDATE `goods` SET `stock`=`stock`+{$number} WHERE `gopen_id`=? AND `enable`=1";
        $r=$this->db->sqlExec($sql,$gopen_id);
        if($r==1){
            $sql2="UPDATE `goods_attr` SET `stock`=`stock`+{$number} WHERE `id`=?";
            $r2=$this->db->sqlExec($sql2,$attr_id);
            if($r2==1){
                return true;
            }
        }
        return false;
    }

    //goods_id
    function modifyCommentAndScore($id,$score,$comment=1){
        $id=(int)$id;
        $comment=(int)$comment;
        $score=(int)$score;
        $sql="UPDATE `goods` SET `comment`=`comment`+$comment,`score`=`score`+$score WHERE `id`=?";
        return $this->db->sqlExec($sql,$id);
    }
} 



